<template>
  <div class="apply-management">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>慢性病报销申请</span>
        </div>
      </template>

      <!-- 身份证验证区域 -->
      <div v-if="!verifiedInsured" class="verify-area">
        <el-form :inline="true" :model="verifyForm" class="demo-form-inline">
          <el-form-item label="身份证号" prop="cardId">
            <el-input
              v-model="verifyForm.cardId"
              placeholder="请输入身份证号"
              clearable
              @keyup.enter="verifyInsured"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="verifyInsured">验证参合信息</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 报销申请表单 -->
      <div v-else>
        <el-descriptions title="参合人基本信息" :column="3" border>
          <el-descriptions-item label="姓名">{{ currentInsured.insured_name }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ currentInsured.card_id }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentInsured.gender }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentInsured.phone }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ currentInsured.address }}</el-descriptions-item>
          <el-descriptions-item label="民族">{{ currentInsured.nation }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions
          v-if="currentMedicalCard"
          title="慢病证信息"
          :column="3"
          border
          class="mt-20"
        >
          <el-descriptions-item label="农合证号">{{ currentMedicalCard.rural_card_no }}</el-descriptions-item>
          <el-descriptions-item label="慢病编码">{{ currentMedicalCard.disease_code }}</el-descriptions-item>
          <el-descriptions-item label="疾病名称">{{ currentMedicalCard.disease_name }}</el-descriptions-item>
          <el-descriptions-item label="有效期">
            {{ formatDate(currentMedicalCard.start_time) }} 至 {{ formatDate(currentMedicalCard.end_time) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="apply-form mt-20">
          <h3>报销申请信息</h3>
          <el-form
            ref="applyForm"
            :model="applyInfo"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="医疗总费用" prop="totalAmount">
              <el-input-number
                v-model="applyInfo.totalAmount"
                :precision="2"
                :step="100"
                :min="0"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="报销年度" prop="applyYear">
              <el-date-picker
                v-model="applyInfo.applyYear"
                type="year"
                format="YYYY"
                value-format="YYYY"
                placeholder="选择年份"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="calculateReimbursement">计算报销金额</el-button>
              <el-button @click="resetForm">重置</el-button>
              <el-button @click="verifiedInsured = false">返回</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 报销金额计算结果 -->
        <el-dialog
          v-model="showResult"
          title="报销金额计算结果"
          width="50%"
        >
          <el-descriptions :column="1" border>
            <el-descriptions-item label="医疗总费用">{{ applyInfo.totalAmount?.toFixed(2) }} 元</el-descriptions-item>
            <el-descriptions-item label="当年封顶线">{{ currentPolicy.max?.toFixed(2) }} 元</el-descriptions-item>
            <el-descriptions-item label="报销比例">{{ (currentPolicy.percentage * 100)?.toFixed(2) }}%</el-descriptions-item>
            <el-descriptions-item label="当年已报销金额">{{ yearlyAmount?.toFixed(2) }} 元</el-descriptions-item>
            <el-descriptions-item label="本次可报销金额">
              <span class="reimburse-amount">{{ calculatedAmount?.toFixed(2) }} 元</span>
            </el-descriptions-item>
          </el-descriptions>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showResult = false">取消</el-button>
              <el-button type="primary" @click="submitApply">确认提交</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟参合人数据
const mockInsured = {
  id: 1,
  insured_name: '张三',
  card_id: '330102199001011234',
  gender: '男',
  nation: '汉族',
  address: '浙江省杭州市上城区某某街道1号',
  phone: '13812345678'
}

// 模拟慢病证数据
const mockMedicalCard = {
  id: 1,
  rural_card_no: 'NH202401001',
  disease_code: 'MB202401001',
  card_id: '330102199001011234',
  disease_name: '高血压',
  start_time: '2024-01-01',
  end_time: '2024-12-31'
}

// 模拟政策数据
const mockPolicy = {
  id: 1,
  year: '2024',
  max: 50000,
  percentage: 0.75
}

// 模拟年度累计数据
const mockYearlyAmount = 20000

const verifyForm = ref({
  cardId: ''
})

const applyInfo = ref({
  totalAmount: 0,
  applyYear: new Date().getFullYear().toString()
})

const rules = {
  totalAmount: [
    { required: true, message: '请输入医疗总费用', trigger: 'blur' }
  ],
  applyYear: [
    { required: true, message: '请选择报销年度', trigger: 'change' }
  ]
}

const verifiedInsured = ref(false)
const currentInsured = ref(null)
const currentMedicalCard = ref(null)
const currentPolicy = ref(null)
const yearlyAmount = ref(0)
const calculatedAmount = ref(0)
const showResult = ref(false)
const applyForm = ref(null)

// 日期格式化
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 验证参合人信息
const verifyInsured = async () => {
  if (!verifyForm.value.cardId) {
    ElMessage.warning('请输入身份证号')
    return
  }

  // 这里应该调用后端API验证参合信息
  // 模拟验证过程
  if (verifyForm.value.cardId === mockInsured.card_id) {
    currentInsured.value = mockInsured
    currentMedicalCard.value = mockMedicalCard
    currentPolicy.value = mockPolicy
    yearlyAmount.value = mockYearlyAmount
    verifiedInsured.value = true
  } else {
    ElMessage.error('未找到参合信息，请确认身份证号是否正确')
  }
}

// 计算报销金额
const calculateReimbursement = () => {
  if (!applyForm.value) return

  applyForm.value.validate((valid) => {
    if (valid) {
      // 验证慢病证是否在有效期内
      const now = new Date()
      const startTime = new Date(currentMedicalCard.value.start_time)
      const endTime = new Date(currentMedicalCard.value.end_time)
      
      if (now < startTime || now > endTime) {
        ElMessage.error('慢病证已过期或未生效')
        return
      }

      // 计算可报销金额
      const { totalAmount } = applyInfo.value
      const { max, percentage } = currentPolicy.value
      const remainingLimit = max - yearlyAmount.value

      if (remainingLimit <= 0) {
        ElMessage.warning('已达到年度封顶线，无法继续报销')
        return
      }

      // 计算本次报销金额
      const theoreticalAmount = totalAmount * percentage
      calculatedAmount.value = Math.min(theoreticalAmount, remainingLimit)
      showResult.value = true
    }
  })
}

// 重置表单
const resetForm = () => {
  applyForm.value?.resetFields()
}

// 提交报销申请
const submitApply = () => {
  // 这里应该调用后端API提交报销申请
  // const applyData = {
  //   card_id: currentInsured.value.card_id,
  //   insured_name: currentInsured.value.insured_name,
  //   rural_card_no: currentMedicalCard.value.rural_card_no,
  //   disease_code: currentMedicalCard.value.disease_code,
  //   disease_name: currentMedicalCard.value.disease_name,
  //   total_amount: applyInfo.value.totalAmount,
  //   apply_amount: calculatedAmount.value,
  //   apply_year: applyInfo.value.applyYear,
  //   operator_id: 1, // 应该从登录用户信息中获取
  //   operator_name: '王经办', // 应该从登录用户信息中获取
  //   area_code: 'AREA001' // 应该从登录信息中获取
  // }

  // 模拟提交成功
  ElMessage.success('报销申请提交成功')
  showResult.value = false
  verifiedInsured.value = false
  resetForm()
}
</script>

<style scoped>
.apply-management {
  padding: 20px;
}

.page-container {
  margin: 0;
  min-height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.verify-area {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.mt-20 {
  margin-top: 20px;
}

.apply-form {
  max-width: 600px;
  margin: 0 auto;
}

.apply-form h3 {
  margin-bottom: 20px;
}

.reimburse-amount {
  color: #409EFF;
  font-size: 18px;
  font-weight: bold;
}
</style>